package threadTest.myCompletableFuture;

import java.util.concurrent.*;

/**
 * 功能描述: 线程编排, 全部都需要执行完毕才可以
 * 2024/08/09
 *
 * @author ZhangYi
 */
public class CompletableFutureAll {

	public static void main(String[] args) {
		ThreadPoolExecutor executor = new ThreadPoolExecutor(2,
				Runtime.getRuntime().availableProcessors(),
				0, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(4), new ThreadPoolExecutor.CallerRunsPolicy());

		String userId = "000000";

		CompletableFuture<String> userInfoCompletableFuture = CompletableFuture.supplyAsync(() -> {
			String currentThreadName = Thread.currentThread().getName();
			System.out.println("正在执行 getUserInfo 任务的线程名称: " + currentThreadName);
			return new UserService().getUserInfo();
		}, executor);

		CompletableFuture<String> userRoleCompletableFuture = CompletableFuture.supplyAsync(() -> {
			String currentThreadName = Thread.currentThread().getName();
			System.out.println("正在执行 getUserRole 任务的线程名称: " + currentThreadName);
			return new UserRoleService().getUserRole(userId);
		}, executor);

		CompletableFuture<String> departmentCompletableFuture = CompletableFuture.supplyAsync(() -> {
			String currentThreadName = Thread.currentThread().getName();
			System.out.println("正在执行 getDepartmentName 任务的线程名称: " + currentThreadName);
			return new DepartmentService().getDepartmentName(userId);
		}, executor);

		CompletableFuture<String> vipCompletableFuture = CompletableFuture.supplyAsync(() -> {
			String currentThreadName = Thread.currentThread().getName();
			System.out.println("正在执行 getVipInfo 任务的线程名称: " + currentThreadName);
			return new VipService().getVipInfo(userId);
		}, executor);

		CompletableFuture<String> otherCompletableFuture = CompletableFuture.supplyAsync(() -> {
			String currentThreadName = Thread.currentThread().getName();
			System.out.println("执行拒绝策略的线程名称是" + currentThreadName);
			return "我是其他信息,为了测试拒绝策略的,因为当前的PC,CPU 的线程是4,队列也是4,所以编程编排5个,一定会触发拒绝策略";
		}, executor);


		// 阻塞主线程，直到所有任务完成
		CompletableFuture.allOf(userInfoCompletableFuture, userRoleCompletableFuture, departmentCompletableFuture, vipCompletableFuture, otherCompletableFuture).join();

		try {
			CompletableFutureResultDto resultDto = new CompletableFutureResultDto(userInfoCompletableFuture.get(),
					userRoleCompletableFuture.get(), departmentCompletableFuture.get(), vipCompletableFuture.get(), otherCompletableFuture.get()
			);
			System.out.println(resultDto);
		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		} catch (ExecutionException e) {
			throw new RuntimeException(e);
		}

		System.out.println("线程执行完毕了");


		// 关闭线程池
		executor.shutdown();
		try {
			if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
				executor.shutdownNow();
				if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
					System.err.println("线程池没有在指定时间内终止");
				}
			}
		} catch (InterruptedException ie) {
			executor.shutdownNow();
			Thread.currentThread().interrupt();
		}
	}
}
